<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/13
 * Time: 10:08
 */

namespace Hrm\Controllers;

use \Admin\Frontend\Controllers\ControllerBase;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmExperience;
use Admin\Models\hrm\XhhrmResource;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\hrm\XhhrmStaffContact;
use Helpers\Assets;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\XhException;
use Phalcon\Mvc\Dispatcher;

class InterviewController extends ControllerBase
{

    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
        if (in_array(strtolower($dispatcher->getActionName()), [
            strtolower('index'),
            strtolower('getStaff'),
            strtolower('authCenter'),
        ])) {
            return true;
        }
        //检查是否已登陆，否则跳转到登陆页面
        if (!User::isLogin()) {
            Main::goLoginPage();
            return false;
        }
        return true;
    }

    public static $enums = [
        'iEmploySource' => [1 => '网站投递', 2 => '猎头推荐', 3 => '招聘会', 4 => '内部员工推荐'],
        'bMarried' => [1 => '是', 0 => '否'],
        'iWorkStatus' => [
            1 => '兼职',
            2 => '实习',
            3 => '全职',
        ],
        'iStaffStatus' => [
            1 => '在职',
            2 => '离职',
            3 => '退休',
        ],
        'iOfferStatus' => [
            1 => '试用',
            2 => '正式'
        ],
        'iUserSex' => ['1' => '男', 2 => '女'],
    ];

    private static $state = [
        0 => '新建',
        1 => '未录取',
        2 => '待入职',
        3 => '未入职',
        4 => '已入职',
        5 => '待录用'
    ];

    /**
     * 设置
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180913
     */
    public function indexAction()
    {
        try {
            $token = $this->request->getQuery('token', 'string');
            if (!$token) {
                return $this->sendViewError('未获取权鉴信息');
            }
            $token = json_decode($this->crypt->decryptBase64($token), true);
            if (!is_array($token)) {
                return $this->sendViewError('非法权鉴信息');
            }
            if ($token['ip'] != Tool::getIp() || $token['userAgency'] != $_SERVER['HTTP_USER_AGENT']) {
                return $this->sendViewError('非法权鉴信息');
            }
            if ($token['endTime'] < time()) {
                return $this->sendViewError('权鉴过期,请重新扫码');
            }

            $this->view->pick('interview/index');
            Assets::layUI();
            Assets::sweetAlert2();
            Assets::easyUIMobile();
            Assets::importJs('js/interview/index.js');
            return $this->view->setVars([
                'enums' => self::$enums
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取个人信息
     *
     * @return string
     *
     * create by dale  20181024
     */
    public function authCenterAction()
    {
//        $this->view->disable();
        try {
            $token = $this->request->getQuery('token', 'string');
            if (!$token) {
                return $this->sendViewError('未获取权鉴信息');
            }
            $token = $this->crypt->decryptBase64($token, 'xh_hrm');
            $tokenArr = explode('_', $token);
            $beSuffix = Tool::getValue($tokenArr, 0);
            if ($beSuffix != 'XhHrmRegister' || count($tokenArr) > 2) {
                return $this->sendViewError('非法权鉴信息');
            }
            $time = Tool::getValue($tokenArr, 1);
            if ($time && $time < time()) {
                return $this->sendViewError('权鉴过期,请重新扫码');
            }
            $arr = [
                'ip' => Tool::getIp(),
                'endTime' => strtotime(' +40 minute'),
                'userAgency' => $_SERVER['HTTP_USER_AGENT']
            ];
            $newToken = urlencode($this->crypt->encryptBase64(json_encode($arr)));
            $this->response->redirect('hrm/interview/index?token='.$newToken);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取员工信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180917
     */
    public function getStaffAction()
    {
        try {
            $key = $this->request->getPost('q', 'string');
            if (!$key) {
                return $this->sendJsonResponse([]);
            }
            $staffArr = XhhrmStaff::find([
                'columns'    => 'iStaffId,sStaffName,sDepIds',
                'conditions' => 'bDelete = 0 and iUserId is not null and sStaffName like :key:',
                'bind'       => ['key' => '%'.$key.'%']
            ])->toArray();
            if ($staffArr) {
                $depArr = XhhrmDepart::getDepEnum();
                foreach ($staffArr as &$staff) {
                    $firstDep = end(array_filter(explode(',', $staff['sDepIds'])));
                    $staff['sStaffName'] .= "({$depArr[$firstDep]})";
                }
            }
            return $this->sendJsonResponse($staffArr);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }
    /**
     * 保存人力资源
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180917
     */
    public function saveSourceAction()
    {
        try {
            $postData = $this->request->getPost();
            $family   = $this->request->getPost('family');
            $itemHistory = $this->request->getPost('itemHistory');
            $tchHistory  = $this->request->getPost('tchHistory');
            $workHistory = $this->request->getPost('workHistory');
            if (!$postData['sStaffName'] || !$postData['sIdentityCode']) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $this->db->begin();
            $obj = XhhrmResource::findFirst([
                'conditions' => 'bDelete = 0 and sStaffName = :sStaffName: and sIdentityCode = :sIdentityCode:',
                'bind'       => ['sStaffName' =>$postData['sStaffName'],'sIdentityCode' => $postData['sIdentityCode']]
            ]);
            if (!$obj) {
                $obj = new XhhrmResource();
            }
            $postData = array_filter($postData);//过滤部分数据
            $obj->assign($postData);
            if (!$obj->save()) {
                throw new XhException('基本信息保存失败');
            }
            if ($family) {
                foreach ($family as $person) {
                    $contactObj = XhhrmStaffContact::findFirst([
                        'conditions' => 'bDelete = 0 and :iSourceId: and sName = :sName:',
                        'bind'       => ['iSourceId' => $obj->iStaffId, 'sName' => $person['sName']]
                    ]);
                    if (!$contactObj) {
                        $contactObj = new XhhrmStaffContact();
                    }
                    $contactObj->assign($person);
                    $contactObj->iSourceId = $obj->iStaffId;
                    if (!$contactObj->save()) {
                        throw new XhException('主要家庭成员保存失败');
                    }
                }
            }
            if ($itemHistory) {
                foreach ($itemHistory as $item) {
                    $itemObj = XhhrmExperience::findFirst([
                        'conditions' => 'bDelete = 0 and :iSourceId: and sName = :sName: and sTag = :sTag: ',
                        'bind'       => ['iSourceId' => $obj->iStaffId, 'sName' => $item['sName'], 'sTag' => 'item']
                    ]);
                    if (!$itemObj) {
                        $itemObj = new XhhrmExperience();
                    }
                    $itemObj->assign($item);
                    $itemObj->iSourceId = $obj->iStaffId;
                    $itemObj->sTag = strtolower('item');
                    if (!$itemObj->save()) {
                        throw new XhException('项目信息保存失败');
                    }
                }
            }
            if ($tchHistory) {
                foreach ($tchHistory as $tch) {
                    $tchObj = XhhrmExperience::findFirst([
                        'conditions' => 'bDelete = 0 and :iSourceId: and sName = :sName: and sTag = :sTag: ',
                        'bind'       => ['iSourceId' => $obj->iStaffId, 'sName' => $tch['sName'], 'sTag' => 'lean']
                    ]);
                    if (!$tchObj) {
                        $tchObj = new XhhrmExperience();
                    }
                    $tchObj->assign($tch);
                    $tchObj->iSourceId = $obj->iStaffId;
                    $tchObj->sTag = strtolower('lean');
                    if (!$tchObj->save()) {
                        throw new XhException('学习经历保存失败');
                    }
                }
            }
            if ($workHistory) {
                foreach ($workHistory as $work) {
                    $workObj = XhhrmExperience::findFirst([
                        'conditions' => 'bDelete = 0 and :iSourceId: and sName = :sName: and sTag = :sTag: ',
                        'bind'       => ['iSourceId' => $obj->iStaffId, 'sName' => $work['sName'], 'sTag' => 'work']
                    ]);
                    if (!$workObj) {
                        $workObj = new XhhrmExperience();
                    }
                    $workObj->assign($work);
                    $workObj->iSourceId = $obj->iStaffId;
                    $workObj->sTag = strtolower('work');
                    if (!$workObj->save()) {
                        throw new XhException('工作经历保存失败');
                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }






}